//
//  ZBLiveViewController.m
//  ZhiBo
//
//  Created by huangtie on 2017/11/2.
//  Copyright © 2017年 huangtie. All rights reserved.
//

#import "ZBLiveViewController.h"
#import <PLVChatManager/PLVChatManager.h>
#import "ZJZDanMu.h"
#import "ZBLiveChannel.h"
#import "ZBAppDelegate.h"

@interface ZBLiveViewController ()<SocketIODelegate,ZBLivePreviewDelegate>

@property (nonatomic, strong) ZBLivePreview *livePreview;
@property (nonatomic, strong) PLVChatSocket *chatSocket;
@property (nonatomic, strong) ZJZDanMu *danmuLayer;

@property (nonatomic , strong) NSTimer *distimer;
@property (nonatomic , assign) NSInteger currentIndex;

@end

@implementation ZBLiveViewController{
    NSString *socketid;
    NSTimer *timer;
}

- (void)dealloc {
    
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor whiteColor];
    
    [self initLivePreview];     // 初始化直播界面及推流器
    [self initChatRoom];        // 添加聊天室
    [self configDanmu];         // 初始化弹幕
    
    if (!self.distimer) {
        [self timerMethod];
        self.distimer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(timerMethod) userInfo:nil repeats:YES];
    }
    
   
    
    [self performBlock:^{
        [self.livePreview startLive];
        [self requestNotice];
    } afterDelay:2];
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    ZBAppDelegate *delegate = (ZBAppDelegate *)[UIApplication sharedApplication].delegate;
    delegate.allowRotate = YES;
}

- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    ZBAppDelegate *delegate = (ZBAppDelegate *)[UIApplication sharedApplication].delegate;
    delegate.allowRotate = NO;
}


- (void)initLivePreview {
    
    CGRect viewFrame;
    if (self.supportedInterfaceOrientation==UIInterfaceOrientationPortrait) {
        viewFrame = self.view.bounds;
    }else {
        viewFrame = CGRectMake(0, 0, SCREEN_HEIGHT, SCREEN_WIDTH);
    }
    
    self.livePreview = [[ZBLivePreview alloc] initWithFrame:viewFrame];
    self.livePreview.supportedInterfaceOrientation = self.supportedInterfaceOrientation;
    //livePreview.audioQuality = self.audioQuality;
    self.livePreview.videoQuality = self.videoQuality;
    self.livePreview.delegate = self;
    
    [self.view addSubview:self.livePreview];
}

-(void)initChatRoom {
    
    __weak typeof(self)weakSelf = self;
    
    [PLVChatRequest getChatTokenSuccess:^(NSString *chatToken) {
        NSLog(@"chat token is %@", chatToken);
        @try {
            // 初始化聊天室
            _chatSocket = [[PLVChatSocket alloc] initChatSocketWithConnectToken:chatToken enableLog:NO];
            _chatSocket.delegate = self;    // 设置代理
            [_chatSocket connect];          // 连接聊天室
        } @catch (NSException *exception) {
            NSLog(@"exceptin:%@, reason:%@",exception.name,exception.reason);
            NSString *message = [NSString stringWithFormat:@"exception name:%@, reason:%@, chatToken:%@",exception.name,exception.reason,chatToken];
            [weakSelf showAlertWithTitle:@"聊天室连接出错" message:message];
        }
    } failure:^(NSString *errorName, NSString *errorDescription) {
        NSLog(@"errorName: %@, errorDescription: %@",errorName,errorDescription);
        NSString *message = [NSString stringWithFormat:@"name:%@, reason:%@",errorName,errorDescription];
        [weakSelf showAlertWithTitle:@"聊天室未连接" message:message];
    }];
}

- (void)configDanmu {
    
    CGRect bounds = self.livePreview.bounds;
    self.danmuLayer = [[ZJZDanMu alloc] initWithFrame:CGRectMake(0, 20, bounds.size.width, bounds.size.height-20)];
    [self.livePreview insertSubview:self.danmuLayer atIndex:0];
}

#pragma mark METHOD
- (void)timerMethod{
    
    NSInteger number = self.currentIndex;
    NSInteger hours = number/3600;
    NSInteger minutes = (number - 3600 * hours) / 60;
    NSInteger seconds = (number - 3600 * hours - 60 * minutes);
    
    NSString *hourstr = [NSString stringWithFormat:@"%02ld", hours];
    NSString *minutestr = [NSString stringWithFormat:@"%02ld", minutes];
    NSString *secondstr = [NSString stringWithFormat:@"%02ld", seconds];
    
    NSString *timeline = [NSString stringWithFormat:@"%@:%@:%@",hourstr,minutestr,secondstr];
    [self.livePreview refreshTimeLabel:timeline];
    
    if (self.currentIndex % 10 == 0) {
        [self requestNotice];
    }
    
    self.currentIndex += 1;
}

#pragma mark Request
- (void)requestNotice
{
    WS(weakSelf)
    [SMNetwork requestOnPOST:SM_Url_GetNoticeMsg param:@{@"token":[SMUserManager shareManager].token , @"channel_id" : [ZBLiveChannel sharedInstance].channelId} completion:^(NSURLSessionDataTask * _Nullable task, id  _Nullable result, NSError * _Nullable error) {
        if (!error) {
            if ([[result objectForKey:@"code"] integerValue] == 200) {
                NSDictionary *data = [result objectForKey:@"data"];
                NSString *content = [data objectForKey:@"content"];
                [weakSelf.livePreview refreshNoticeText:content];
            }else{
                [weakSelf.livePreview refreshNoticeText:@""];
                [weakSelf.view makeToast:[result objectForKey:@"msg"]];
            }
        }else{
            [weakSelf.livePreview refreshNoticeText:@""];
            [weakSelf.view makeToast:TIP_LOAD_FAILED];
        }
    }];
}

- (void)requestEndlive
{
    [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    WS(weakSelf)
    [SMNetwork requestOnPOST:SM_Url_Endlive param:@{@"token":[SMUserManager shareManager].token , @"channel_id" : [ZBLiveChannel sharedInstance].channelId} completion:^(NSURLSessionDataTask * _Nullable task, id  _Nullable result, NSError * _Nullable error) {
        [MBProgressHUD hideHUDForView:weakSelf.view animated:YES];
        if (!error) {
            if ([[result objectForKey:@"code"] integerValue] == 200) {
                [weakSelf dismissViewControllerAnimated:YES completion:nil];
            }else{
                [weakSelf.view makeToast:@"关闭直播请求失败，请重试！"];
            }
        }else{
            [weakSelf.view makeToast:@"关闭直播请求失败，请重试！"];
        }
    }];
}

#pragma mark - chatSocket delegate 事件

/** socket成功连接上聊天室*/
- (void)socketIODidConnect:(PLVChatSocket *)chatSocket {
    NSLog(@"socket connected");
    socketid = chatSocket.socketId;
    timer = [NSTimer scheduledTimerWithTimeInterval:60.0 target:self selector:@selector(onTime_tick) userInfo:nil repeats:YES];
    
    NSDictionary *userInfo = [ZBLiveChannel sharedInstance].userInfo;
    // 登录聊天室
    [chatSocket loginStreamerChatRoomWithChannelId:userInfo[@"channelId"] nickName:@"主持人" avatar:userInfo[@"avatar"]];
}


/** socket收到聊天室信息*/
- (void)socketIODidReceiveMessage:(PLVChatSocket *)chatSocket withChatObject:(PLVChatObject *)chatObject {
    
    NSLog(@"messageType: %ld",chatObject.messageType);
    
    switch (chatObject.messageType) {
        case PLVChatMessageTypeCloseRoom:
        case PLVChatMessageTypeOpenRoom: {
            NSLog(@"房间暂时关闭/打开");
        }
            break;
        case PLVChatMessageTypeGongGao: {
            NSLog(@"GongGao: %@",chatObject.messageContent);
            if (self.danmuLayer) {
                [self.danmuLayer insertDML:[@"公告：" stringByAppendingString:chatObject.messageContent]];           // 发送弹幕
            }
        }
            break;
        case PLVChatMessageTypeSpeak: {
            NSLog(@"messageContent: %@",chatObject.messageContent);
            if (chatObject.messageContent && ![chatObject.messageContent isKindOfClass:[NSNull class]]) {
                if (self.danmuLayer) {
                    [self.danmuLayer insertDML:chatObject.messageContent];                                          // 发送弹幕
                }
            }
        }
            break;
        case PLVChatMessageTypeError:
            break;
        default:
            break;
    }
}

/** socket和聊天室失去连接*/
- (void)socketIODidDisconnect:(PLVChatSocket *)chatSocket {
    NSLog(@"socket disconnect");
}

/** socket连接聊天室出错*/
- (void)socketIOConnectOnError:(PLVChatSocket *)chatSocket {
    NSLog(@"socket error");
}

/** socket尝试重新连接聊天室时*/
- (void)socketIOReconnect:(PLVChatSocket *)chatSocket {
    NSLog(@"socket reconnect");
}

/** 当socket连接开始重新连接聊天室*/
- (void)socketIOReconnectAttempt:(PLVChatSocket *)chatSocket {
    NSLog(@"socket reconnectAttempt");
}



#pragma mark - 转屏相关
- (BOOL)shouldAutorotate
{
    ZBAppDelegate *delegate = (ZBAppDelegate *)[UIApplication sharedApplication].delegate;
    return delegate.allowRotate;
}

- (UIInterfaceOrientationMask)supportedInterfaceOrientations {
    
    if (_supportedInterfaceOrientation==UIInterfaceOrientationPortrait) {
        return UIInterfaceOrientationMaskPortrait;
    }else {
        return UIInterfaceOrientationMaskLandscape;
    }
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation {
    return YES;
}

- (void)onTime_tick {
    // 每分钟刷新次聊天室后台，防止被kill掉连接
    [PLVChatRequest requestWithSocketId:socketid failure:^(NSInteger responseCode, NSString *errorReason) {
        NSLog(@"responseCode:%ld",responseCode);
    }];
}

#pragma mark Delegate-LivePreview
- (void)livePreviewDidClickQunit
{
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"提示" message:@"是否退出当前直播？" preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction *continueAction = [UIAlertAction actionWithTitle:@"退出" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
        [self requestEndlive];
    }];
    UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction *action) {
    }];
    [alertController addAction:continueAction];
    [alertController addAction:cancelAction];
    [self presentViewController:alertController animated:YES completion:nil];
}

- (void)liveDidConnectError
{
    [self dismissViewControllerAnimated:YES completion:^{
        [GETWINDOW makeToast:@"直播连接出错！"];
    }];
}

#pragma mark - 重写本控制类dismissViewControllerAnimated：方法

- (void)dismissViewControllerAnimated:(BOOL)flag completion:(void (^)(void))completion {
    ZBAppDelegate *delegate = (ZBAppDelegate *)[UIApplication sharedApplication].delegate;
    delegate.allowRotate = NO;
    
    if (timer) {
        [timer invalidate];                 // 清除定时器
        timer = nil;
    }
    if (self.distimer) {
        [self.distimer invalidate];                 // 清除定时器
        self.distimer = nil;
    }
    [self.chatSocket disconnect];           // 断开聊天室
    [self.chatSocket removeAllHandlers];    // 移除所有监听事件
    self.chatSocket = nil;                  // 将chatSocket置空(待测试)
    
    [super dismissViewControllerAnimated:flag completion:completion];
}

#pragma mark - 私有方法

- (void)showAlertWithTitle:(NSString *)title message:(NSString *)message {
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:title message:message preferredStyle:UIAlertControllerStyleAlert];
    [alertController addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleDefault handler:nil]];
    dispatch_async(dispatch_get_main_queue(), ^{
        [self presentViewController:alertController animated:YES completion:nil];
    });
}

@end
